import { ref, Ref, shallowRef } from 'vue';
import { RequestSuccessData } from 'axios';
// import type { MaybeRef } from "@vueuse/core";

export interface useRequestOptions {
  loading?: Ref<boolean>;
}

interface Request<T, U> {
  (data: U): Promise<RequestSuccessData<T>>;
}

export const useRequest = <T, U = null>(
  request: Request<T, U>,
  dataOpt: U,
  options?: useRequestOptions
) => {
  const result = ref<RequestSuccessData<T> | undefined>();
  const error = shallowRef<Error | undefined>();

  // 获取loading状态
  const loading = options?.loading || ref(true);

  // 加载中
  loading.value = true;

  console.log('request', request);

  // 开始请求
  request(dataOpt)
    .then((res) => {
      // 加载结束
      loading.value = false;
      // 获取数据
      result.value = res;
    })
    .catch((err) => {
      console.log('useRequest Error', err);
      error.value = err;
    });

  return {
    result,
    error
  };
};
